<?php

class Commerce_CheckoutController extends Commerce_Controller_Action {

	function init(){	
		parent::init();				
	}

	function indexAction(){
		$request = new Cts_Request($this->getRequest());
		
		if( $this->_auth->hasIdentity() ){
			$commerce_users_table = new CommerceUsers();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
		} else {
			$commerce_user = false;
		}
		
		## If logged in, or set to use guest account
		if( !empty($commerce_user) || ($request->has('as') && $request->as=='guest') ){
			$Cart = new Magento_Curl_Cart();
			$Catalog = new CommerceMagentoCatalog();
			
			$locale = $Catalog->formatStoreId( $this->locale_code );
			
			$cart_url  = Cts_Registry::get('magento_user_scheme').'://';
			$cart_url .= Cts_Registry::get('magento_user_host').'/';
			
			if( Cts_Registry::get('magento_user_locale_code')=='1' ){
				$cart_url .= $locale.'/';
			}
			
			$cart_url .= 'checkout/onepage/index/';
			
			if( empty($commerce_user) ){
				## Guest Checkout
				$cart_url .= 'guest';
			}
			
			if( !empty($this->session->magento_curl_session_id) ){
				if( Cts_Registry::get('magento_user_locale_code')=='1' && array_key_exists($locale, $this->session->magento_curl_session_id)  ){
					$cart_url .= '?SID='.$this->session->magento_curl_session_id[ $locale ];
				} elseif( is_string($this->session->magento_curl_session_id) ){
					$cart_url .= '?SID='.$this->session->magento_curl_session_id;
				}
			}
			
			header('Location: '.$cart_url);	exit;
		} else {
			
			$this->_redirect('/default/auth/login/for/checkout/url/'.base64_encode('/commerce/checkout/'));
		}
	}
	
	function successAction(){
		$request = new Cts_Request($this->getRequest());
		
		if( $request->has('order') && $request->has('auth') ){
			$order = $this->validateOrderNumber( (string)$request->order );
			$auth = $request->auth;
			
			if( $order ){
				try {
					## Get the order information
					$orders_table = new CommerceMagentoOrders();
					$order_info = $orders_table->getOrderInfo( $order );
				} catch( Exception $e ){
					$this->successFailed();
				}
				
				## Check the IP address
				if( $order_info['remote_ip'] == $_SERVER['REMOTE_ADDR'] ){
					## Recreate the security hash and compare it
					$hash = md5( $order_info['created_at'].'_'.$order_info['customer_email'] );
					if( $hash == $request->auth ){
						$server_timezone = date_default_timezone_get();
						$server_timezone_obj = new DateTimeZone( $server_timezone );
						$server_datetime = new DateTime('now', $server_timezone_obj);
						$server_offset = (string)$server_timezone_obj->getOffset( $server_datetime );
						
						$server_real_offset = (string)($server_offset*-1);
						if($server_real_offset>0) $server_real_offset = "+{$server_real_offset}";
						
						## Check the timeout
						$timer = Cts_Registry::get('guest_checkout_success_view_time');
						$current = date('Y-m-d H:i:s', strtotime( date('Y-m-d H:i:s')." {$server_real_offset} seconds" ));
						$limit   = date('Y-m-d H:i:s', strtotime($order_info['created_at']." +{$timer} seconds"));
						
						if( $current <= $limit ){
							//d($order_info);
							
							## Add Google Analytics tracking
							if( Cts_Registry::get('analytics_is_enabled')=='1' && Cts_Registry::get('analytics_track_commerce')=='1' ){
								if( isset($order_info['items']) && is_array($order_info['items']) ){
									$tracker = array();
									$tracker_items = array();
									
									## Get general order (transaction) information
									$tracker['id']			= addslashes( $order_info['increment_id'] );
									$tracker['store']		= addslashes( str_replace("\n", ', ', $order_info['store_name']) );
									$tracker['total']		= addslashes( $order_info['subtotal'] );
									$tracker['tax']			= addslashes( $order_info['tax_amount'] );
									$tracker['shipping']	= addslashes( $order_info['shipping_amount'] );
									$tracker['city']		= addslashes( $order_info['shipping_address']['city'] );
									$tracker['region']		= addslashes( $order_info['shipping_address']['region'] );
									$tracker['country']		= addslashes( $order_info['shipping_address']['country_id'] );
									
									$Catalog = new CommerceMagentoCatalog();
									$storeView = (isset($order_info['store_id'])) ? $order_info['store_id'] : $this->locale_code;
									
									foreach( $order_info['items'] as $item ){
										try {
											$product = $Catalog->getProduct( $item['product_id'], $storeView );
											if( is_array($product['categories']) && !empty($product['categories']) ){
												$_category = $Catalog->getCategory( $product['categories'][0] );
												$category = $_category['name'];
											}
										} catch( Exception $e ){
											$category = 'Unknown';
										}
										
										$tracker_items[] = array(
											'id'		=> addslashes( $item['product_id'] ),
											'sku'		=> addslashes( $item['sku'] ),
											'name'		=> addslashes( $item['name'] ),
											'category'	=> addslashes( $category ),
											'price'		=> addslashes( $item['price'] ),
											'qty'		=> addslashes( $item['qty_ordered'] ),
										);
									}
								}
								
								$this->view->order_tracking = $tracker;
								$this->view->order_tracking_items = $tracker_items;
							}
							
							$this->view->order = $order_info;
							return;
						}
					}
				}
			}
		}
		
		$this->successFailed();
	}
	
	function validateOrderNumber( $order, $supress=false ){
		if( ctype_digit($order) ){
			return $order;
		} else {
			if( $supress===false ){
				$order = base64_decode($order);
				return $this->validateOrderNumber( $order, true );
			} else {
				return false;
			}
		}
	}
	
	function successFailed(){
		if( $this->_auth->hasIdentity() ){
			$commerce_users_table = new CommerceUsers();
			$commerce_user = $commerce_users_table->findArray($this->_identity->username);
		} else {
			$commerce_user = false;
		}
		
		if( !empty($commerce_user) ){
			## If logged in, redirect to the order view page under my account
			$this->_redirect('/commerce/account/orders');
		} else {
			## If not logged in, redirect to the login page
			$this->_redirect('/default/auth/login');
		}
	}
}
